<template>
  <div>
    <el-form
      ref="dataFormRef"
      v-loading="loading"
      :model="state.form"
      :rules="dataRules"
      label-width="100px"
      :disabled="operType === 'view'"
    >
      <el-row :gutter="24">
        <el-divider>审批人设置</el-divider>
        <el-col :span="12" class="mb20">
          <el-form-item label="跳转任务类型" prop="jumpJobType">
            <el-tooltip placement="top">
              <template #content>
                标识【待跳转任务】的【任务类型】是审批人还是审批角色。当待跳转任务存在办理人/角色时，可不选择
              </template>
              <el-radio-group
                v-model="state.form.jumpJobType"
                @change="handleUserOrRoleType"
              >
                <el-radio
                  v-for="(item, index) in DIC_PROP.JOB_USER_TYPE"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-tooltip>
            <el-tooltip v-if="state.form.jumpJobType" placement="top">
              <template #content
                >当待跳转任务存在办理人/角色时，可不选择</template
              >
              <el-button
                text
                type="primary"
                icon="delete"
                @click="clearJumpType"
                >清空</el-button
              >
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-divider>任意跳转设置</el-divider>
        <el-col :span="12" class="mb20">
          <el-form-item label="流程名称" prop="defFlowId">
            <el-input
              v-model="state.form.flowName"
              placeholder="流程名称"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="流程实例ID" prop="flowInstId">
            <el-input
              v-model="state.form.flowInstId"
              placeholder="流程实例ID不能为空"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="目标节点" prop="toRunNodeId">
            <el-tooltip
              placement="top"
              content="若不选择具体的【待跳转人/角色】，则默认会跳转到该节点下的全部办理人/角色"
            >
              <CommonSelect
                v-model:defaultValue="state.form.toRunNodeId"
                :placeholder="translate('请选择跳转节点')"
                label="nodeName"
                value="id"
                :url="jumpNodeListUrl"
                auto-query
                :query-params="state.nodeParams"
                @change="handleToRunNodeIdChange"
              />
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col v-if="state.form.jumpJobType === '0'" :span="12" class="mb20">
          <el-form-item label="待跳转人" prop="handleUserId">
            <el-tooltip placement="top">
              <template #content>{{
                validateNull(state.form.handleUserId) ? userIdText : userIdText2
              }}</template>
              <CommonSelect
                v-model:defaultValue="state.form.handleUserId"
                :placeholder="translate('请选择待跳转人')"
                label="userName"
                value="id"
                :url="nodeUserListUrl"
                auto-query
              />
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col v-if="state.form.jumpJobType === '1'" :span="12" class="mb20">
          <el-form-item label="待跳转角色" prop="handleRoleId">
            <el-tooltip placement="top">
              <template #content>{{
                validateNull(state.form.handleRoleId) ? roleIdText : roleIdText2
              }}</template>
              <CommonSelect
                v-model:defaultValue="state.form.handleRoleId"
                :placeholder="translate('请选择待跳转角色')"
                label="roleName"
                value="id"
                :url="nodeRoleListUrl"
                auto-query
              />
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <div style="margin-left: 30px">
          什么是待跳转人/角色？当待跳转人或角色为空时，则默认会跳转到该节点下的全部办理人/角色。当待跳转人或角色不为空时，则会跳转到该节点下指定的办理人员或角色（{{
            userRoleIdText
          }}）
        </div>
        <el-button
          type="primary"
          icon="circle-check"
          :loading="loading"
          @click="handleUpdate"
          >确认</el-button
        >
      </span>
    </footer>
  </div>
</template>

<script setup lang="ts" name="RunAnyJumpForm">
import { translate } from "@/plugins/i18n";
import { DIC_PROP } from "@/flow/support/dict-prop";
import { PROP_CONST } from "@/flow/support/prop-const";
import { validateNull } from "@/utils/validate";
import { useMessage } from "@/hooks/message";
import * as doJob from "@/api/flow/jobtask";
import CommonSelect from "@/components/commonSelect.vue";

const props = defineProps({
  currJob: {
    type: Object,
    default: null
  },
  comment: {
    type: String,
    default: null
  }
});

const $emit = defineEmits(["confirm"]);

const $message = useMessage();
const dataFormRef = ref();
const loading = ref(false);
const operType = ref("");

// 提交表单数据
const state = reactive({
  form: {
    defFlowId: "",
    flowName: "",
    jumpJobType: "",
    flowInstId: "",
    toRunNodeId: "",
    toFlowNodeId: "",
    handleUserId: "",
    handleRoleId: ""
  },
  nodeParams: {
    runNodeId: props.currJob.runNodeId
  }
});

// 定义校验规则
const dataRules = ref({
  defFlowId: [{ required: true, message: "流程名称不能为空", trigger: "blur" }],
  flowInstId: [
    { required: true, message: "流程实例ID不能为空", trigger: "blur" }
  ],
  toRunNodeId: [
    { required: true, message: "到达节点名称不能为空", trigger: "blur" }
  ]
});

const jumpNodeListUrl = computed(() => {
  return `/esflow/run/node/jump/${state.form.flowInstId}`;
});

const nodeUserListUrl = computed(() => {
  return `/esflow/run/job/list/user/${state.form.toRunNodeId}`;
});

const nodeRoleListUrl = computed(() => {
  return `/esflow/run/job/list/role/${state.form.toRunNodeId}`;
});

const userIdText =
  "注：当前待跳转节点下可候选待跳转人为空，请指定待跳转人即为其分配办理人";
const userIdText2 =
  "注：当待跳转人为空时，则默认会跳转到当前节点显示的全部办理人";
const roleIdText =
  "注：当前待跳转节点下可候选待跳转角色为空，请指定待跳转角色即为其分配办理角色";
const roleIdText2 =
  "注：当待跳转角色为空时，则默认会跳转到当前节点显示的全部办理角色";
const userRoleIdText =
  "注：当待跳转节点下任务不存在办理人/角色时，请指定待跳转人或角色即为其分配办理人/角色";

const handleToRunNodeIdChange = (val, item) => {
  state.form.toRunNodeId = val;
  state.form.toFlowNodeId = item.flowNodeId;
};

function initJobData() {
  Object.assign(state.form, props.currJob);
  if (props.currJob.runFlow) {
    state.form.flowName = props.currJob.runFlow.flowName;
  }
}

function handleUserOrRoleType(type) {
  if (type === DIC_PROP.JOB_USER_TYPE[0].value) {
    state.form.handleRoleId = null;
  } else if (type === DIC_PROP.JOB_USER_TYPE[1].value) {
    state.form.handleUserId = null;
  }
}

function clearJumpType() {
  state.form.jumpJobType = "";
  state.form.handleUserId = null;
  state.form.handleRoleId = null;
}

async function handleUpdate() {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  let a = validateNull(state.form.handleUserId) && !state.form.handleUserId;
  let b = validateNull(state.form.handleRoleId) && !state.form.handleRoleId;
  if (a && b) {
    $message.warning(userRoleIdText);
    return;
  }
  // 指定待跳转人/角色
  if (state.form.jumpJobType === DIC_PROP.JOB_USER_TYPE[0].value) {
    if (a) {
      $message.warning(userIdText);
      return;
    }
  } else if (state.form.jumpJobType === DIC_PROP.JOB_USER_TYPE[1].value) {
    if (b) {
      $message.warning(roleIdText);
      return;
    }
    state.form.handleRoleId =
      PROP_CONST.COMMON.userRolePrefix + state.form.handleRoleId;
  }
  loading.value = true;
  try {
    const params = {
      id: props.currJob.id,
      toFlowNodeId: state.form.toFlowNodeId,
      toRunNodeId: state.form.toRunNodeId,
      jumpJobType: state.form.jumpJobType,
      handleUserId: state.form.handleUserId,
      handleRoleId: state.form.handleRoleId,
      comment: props.comment
    };
    doJob.anyJump(params).then(res => {
      if (res.code === 200) {
        useMessage().success("跳转成功");
        $emit("confirm", state.form);
        setTimeout(() => {
          // 异步异常
          loading.value = false;
        }, 3000);
      } else {
        useMessage().error(res.msg);
      }
    });
  } catch (e) {
    loading.value = false;
  }
}

// 监听双向绑定
watch(
  () => props.currJob.id,
  val => {
    initJobData();
  }
);

onMounted(() => {
  initJobData();
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
